package com.lex.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lex.common.api.CommonResult;
import com.lex.data.admin.model.LexSysParams;
import com.lex.data.admin.service.LexSysParamsService;
import com.lex.entity.sysconfig.SysConfigDto;
import com.lex.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lex.common.redis.RedisService;
@Service
public class SysConfigServiceImpl implements SysConfigService {

    @Autowired
    private LexSysParamsService lexSysParamsService;

    @Autowired
    private RedisService redisService;

    /**
     * 保存配置参数
     * @param sysConfigDto
     * @return
     */
    @Override
    public CommonResult saveConfig(SysConfigDto sysConfigDto) {
        //判断是否存在
        LexSysParams lexSysParams = lexSysParamsService.getOne(new QueryWrapper<LexSysParams>()
                .eq("param_type", sysConfigDto.getKey()));
        boolean save = false;
        if (lexSysParams == null) {
            //新增
            LexSysParams add_param = new LexSysParams();
            add_param.setParamType(sysConfigDto.getKey());
            add_param.setParamValue(sysConfigDto.getValue());
            save = lexSysParamsService.save(add_param);
        }else{
            //更新
            lexSysParams.setParamValue(sysConfigDto.getValue());
            save = lexSysParamsService.updateById(lexSysParams);
        }
        if (save) {
            //删除redis缓存
            redisService.del(sysConfigDto.getKey());
            return CommonResult.success(null, "配置保存成功");
        }
        return CommonResult.failed("配置保存失败");
    }

    /**
     * 获取配置参数
     * @param key
     * @return
     */
    @Override
    public CommonResult getConfig(String key) {
        //首先读取redis缓存
        String value = (String) redisService.get(key);
        if (value != null) {
            return CommonResult.success(value);
        }
        //缓存中没有，从数据库中读取
        LexSysParams lexSysParams = lexSysParamsService.getOne(new QueryWrapper<LexSysParams>()
                .eq("param_type", key));
        if (lexSysParams != null) {
            //将配置保存到redis缓存中
            redisService.set(key, lexSysParams.getParamValue());
            return CommonResult.success(lexSysParams.getParamValue());
        }
        return CommonResult.failed("配置不存在");
    }
}
